﻿using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using DevExpress.Web.ASPxCallbackPanel;
using DevExpress.Web.ASPxGridView;
using DevExpress.Web.ASPxEditors;
using DevExpress.Web.ASPxClasses;

namespace Project_Udrinkwater.Stock
{
    public partial class Stocking : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                string dateNow = ConvestToDate((DateTime.Now).ToShortDateString());
                Session["cStart"] = "0001-01-01";
                Session["cEnd"] = dateNow;
            }
        }

        protected void ASPxGridView2_BeforePerformDataSelect(object sender, EventArgs e)
        {
            Session["Stock_ID"] = (sender as ASPxGridView).GetMasterRowKeyValue();
         

        }

        

        protected void ASPxGridView2_CustomColumnDisplayText(object sender, ASPxGridViewColumnDisplayTextEventArgs e)
        {
            if (e.Column.FieldName == "Product_ID")
            {

            SqlConnection objConnIndicatorID = new SqlConnection();
            string strConnStringIndicatorID = null;
            strConnStringIndicatorID = ConfigurationManager.ConnectionStrings["DB_UdrinkConnectionString"].ConnectionString;
            objConnIndicatorID.ConnectionString = strConnStringIndicatorID;
            objConnIndicatorID.Open();
            SqlDataAdapter dtAdapterIndicatorID;
            DataTable dtIndicatorID = new DataTable();
            string strSQLIndicatorID = "SELECT Product_Name   from TB_Product,TB_Stock_List WHERE TB_Product.Product_ID=TB_Stock_List.Product_ID AND TB_Stock_List.Stock_ID="+int.Parse(Session["Stock_ID"].ToString())+"";


            dtAdapterIndicatorID = new SqlDataAdapter(strSQLIndicatorID, objConnIndicatorID);
            dtAdapterIndicatorID.Fill(dtIndicatorID);


                if (dtIndicatorID.Rows.Count > 0)
                {
                    string strProductName = dtIndicatorID.Rows[0]["Product_Name"].ToString();
                    e.DisplayText = strProductName.ToString();
                }
            }
        }

        protected void ASPxGridView2_CellEditorInitialize(object sender, ASPxGridViewEditorEventArgs e)
        {
            ASPxGridView grid = (ASPxGridView)sender;
            switch (e.Column.FieldName)
            {
                case "Floor_ID":
                    InitializeCombo(e, "Warehouse_ID", SqlDataSource2, cmbCombo2_OnCallback, grid);
                    break;
                case "In_Stock":
                    InitializeCombo(e, "Product_ID", sqlProductAmount, cmbCombo3_OnCallback, grid);
                    break;
                default:
                    break;
            }
            
        }

       
           private void cmbCombo2_OnCallback(object source, CallbackEventArgsBase e)
    {
        FillCombo(source as ASPxComboBox, e.Parameter, SqlDataSource2);
    }


           private void cmbCombo3_OnCallback(object source, CallbackEventArgsBase e)
           {
               FillCombo1(source as ASPxComboBox, e.Parameter, sqlProductAmount);
           }

    protected void InitializeCombo(ASPxGridViewEditorEventArgs e,string parentComboName, SqlDataSource source, CallbackEventHandlerBase callBackHandler, ASPxGridView grid)
    {

        string id = string.Empty;
        if (!grid.IsNewRowEditing)
        {
            object val = grid.GetRowValuesByKeyValue(e.KeyValue, parentComboName);
            id = (val == null || val == DBNull.Value) ? null : val.ToString();
        }
        ASPxComboBox combo = e.Editor as ASPxComboBox;
        if (combo != null)
        {
            // unbind combo
            combo.DataSourceID = null;
            FillCombo(combo, id, source);
            combo.Callback += callBackHandler;
        }
        return;
    }

    protected void FillCombo(ASPxComboBox cmb, string id, SqlDataSource source)
    {
        cmb.Items.Clear();
        // trap null selection
        if (string.IsNullOrEmpty(id)) return;

        // get the values
        source.SelectParameters[0].DefaultValue = id;
        DataView view = (DataView)source.Select(DataSourceSelectArguments.Empty);
        foreach (DataRowView row in view)
        {
            cmb.Items.Add(row[1].ToString(), row[0]);
        }
    }



    protected void InitializeCombo1(ASPxGridViewEditorEventArgs e,string parentComboName, SqlDataSource source, CallbackEventHandlerBase callBackHandler, ASPxGridView grid)
    {

        string id = string.Empty;
        if (!grid.IsNewRowEditing)
        {
            object val = grid.GetRowValuesByKeyValue(e.KeyValue, parentComboName);
            id = (val == null || val == DBNull.Value) ? null : val.ToString();
        }
        ASPxComboBox combo = e.Editor as ASPxComboBox;
        if (combo != null)
        {
            // unbind combo
            combo.DataSourceID = null;
            FillCombo1(combo, id, source);
            combo.Callback += callBackHandler;
        }
        return;
    }

    protected void FillCombo1(ASPxComboBox cmb, string id, SqlDataSource source)
    {
        cmb.Items.Clear();
        // trap null selection
        if (string.IsNullOrEmpty(id)) return;

        // get the values
        source.SelectParameters[0].DefaultValue = id;
        DataView view = (DataView)source.Select(DataSourceSelectArguments.Empty);
        foreach (DataRowView row in view)
        {
            cmb.Items.Add(row[0].ToString(), row[0]);
        }
    }

        private DataTable Validater ( )
        {
            string Instock ="" ;
            DataTable sa = new DataTable();
            DataSourceSelectArguments args = new DataSourceSelectArguments();
            DataView dvSql = (DataView)sqlValStock.Select(DataSourceSelectArguments.Empty);
            sa = dvSql.ToTable();
            
            return sa;
            
            
        }

        protected void ASPxGridView2_RowValidating(object sender, DevExpress.Web.Data.ASPxDataValidationEventArgs e)
        {
            
            string PIDFormGv = "";
            Session["ssProductID"] = null;
            PIDFormGv = e.NewValues["Product_ID"].ToString();
            Session["ssProductID"] = PIDFormGv;
            DataTable dataTable = Validater();
            int Instock = Convert.ToInt32(dataTable.Rows[0]["In_Stock"].ToString());
               
            if (Instock <= 20)
            {
                if (Convert.ToInt32(e.NewValues["Transfer_Category_ID"]) == 1 )
                {
                    ////
                }
            }

        }

        protected void sqlValStock_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            e.Command.Parameters["@Product_ID"].Value = Session["ssProductID"].ToString();
        }

        protected void lkDetail_Command(object sender, CommandEventArgs e)
        {

            string Stock_ID = e.CommandArgument.ToString();
            Session["sStock_ID"] = Stock_ID;
            Response.Redirect("StockList.aspx");
        }

        protected void ASPxButton7_Click(object sender, EventArgs e)
        {
            string a = ConvestToDate((deStart.Date).ToShortDateString());
            string b = ConvestToDate((edEnd.Date).ToShortDateString());
            Session["cStart"] = a;
            Session["cEnd"] = b;
            SqlStockListSert.Select(DataSourceSelectArguments.Empty);
            ASPxGridView1.DataBind();
        }

        public string ConvestToDate(string s)
        {
            string day = "";
            string mount = "";
            string years = "";

            try
            {
                string[] stemp = s.Split('/');
                mount = (stemp[0]);
                day = (stemp[1]);
                years = (stemp[2]);
                if (Convert.ToInt32(years) > 2300)
                {
                    years = (Convert.ToInt32(years) - 543).ToString();
                }

                return (years + "-" + mount + "-" + day);
            }
            catch (Exception)
            {

            }
            return (years + "-" + mount + "-" + day);
        }

        protected void SqlStockListSert_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            e.Command.Parameters["@sStart"].Value = Session["cStart"].ToString();
            e.Command.Parameters["@sEnd"].Value = Session["cEnd"].ToString();
        }

        protected void ASPxButton8_Click(object sender, EventArgs e)
        {
            string a = ConvestToDate((deStart0.Date).ToShortDateString());
            string b = ConvestToDate((edEnd0.Date).ToShortDateString());
            Session["cStart"] = a;
            Session["cEnd"] = b;
            SqlDataSource1.Select(DataSourceSelectArguments.Empty);
            gridMain.DataBind();
        }

        protected void SqlDataSource1_Selecting(object sender, SqlDataSourceSelectingEventArgs e)
        {
            e.Command.Parameters["@sStart"].Value = Session["cStart"].ToString();
            e.Command.Parameters["@sEnd"].Value = Session["cEnd"].ToString();
        }

        protected void ASPxButton9_Click(object sender, EventArgs e)
        {
            Panel1.Visible = false;
            Panel2.Visible = true;
        }

        protected void ASPxButton10_Click(object sender, EventArgs e)
        {
            Panel1.Visible = true;
            Panel2.Visible = false;
        }

        protected void ASPxButton11_Click(object sender, EventArgs e)
        {
            string a = ConvestToDateN((deStart0.Date).ToShortDateString());
            string b = ConvestToDateN((edEnd0.Date).ToShortDateString());
            if (a == "1-1-0001" && b == "1-1-0001")
            {
                a = " ทั้งหมด ";
                b = " ทั้งหมด ";
            }
            ASPxGridViewExporter1.ReportHeader = "\t\tรายงานใบเบิก/รับสินค้า\n\t ตั้งแต่วันที่:" + a + " ถึงวันที่:" + b + "\n";
            ASPxGridViewExporter1.WritePdfToResponse();
            
        }

        protected void ASPxButton12_Click(object sender, EventArgs e)
        {
            string a = ConvestToDateN((deStart.Date).ToShortDateString());
            string b = ConvestToDateN((edEnd.Date).ToShortDateString());
            if (a == "1-1-0001" && b == "1-1-0001")
            {
                a = " ทั้งหมด ";
                b = " ทั้งหมด ";
            }
            ASPxGridViewExporter2.ReportHeader = "\t\tรายงานเบิก/รับสินค้า\n\t ตั้งแต่วันที่:" + a + " ถึงวันที่:" + b + "\n";
            ASPxGridViewExporter2.WritePdfToResponse();
        }
        public string ConvestToDateN(string s)
        {
            string day = "";
            string mount = "";
            string years = "";

            try
            {
                string[] stemp = s.Split('/');
                mount = (stemp[0]);
                day = (stemp[1]);
                years = (stemp[2]);
                if (Convert.ToInt32(years) > 2300)
                {
                    years = (Convert.ToInt32(years) - 543).ToString();
                }

                return (day + "-" + mount + "-" + years);
            }
            catch (Exception)
            {

            }
            return (day + "-" + mount + "-" + years);
        }

        protected void ASPxButton13_Click(object sender, EventArgs e)
        {
            string a = ConvestToDateN((deStart0.Date).ToShortDateString());
            string b = ConvestToDateN((edEnd0.Date).ToShortDateString());
            if (a == "1-1-0001" && b == "1-1-0001")
            {
                a = " ทั้งหมด ";
                b = " ทั้งหมด ";
            }
            ASPxGridViewExporter1.ReportHeader = "\t\tรายงานใบเบิก/รับสินค้า\n\t ตั้งแต่วันที่:" + a + " ถึงวันที่:" + b + "\n";
            ASPxGridViewExporter1.WriteXlsToResponse();
        }

        protected void ASPxButton14_Click(object sender, EventArgs e)
        {
            string a = ConvestToDateN((deStart.Date).ToShortDateString());
            string b = ConvestToDateN((edEnd.Date).ToShortDateString());
            if (a == "1-1-0001" && b == "1-1-0001")
            {
                a = " ทั้งหมด ";
                b = " ทั้งหมด ";
            }
            ASPxGridViewExporter2.ReportHeader = "\t\tรายงานเบิก/รับสินค้า\n\t ตั้งแต่วันที่:" + a + " ถึงวันที่:" + b + "\n";
            ASPxGridViewExporter2.WriteXlsToResponse();
        }
       
        
    }
}